<?php

namespace bricks\linkage;

use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;

class Linkage extends Widget
{
    public $name;

    public $items = [];

    public $clientOptions = [];

    public $options = [
        'style' => 'max-width: 150px; margin-right: 15px; display: inline-block;'
    ];

    public $onChange;

    public function run()
    {
        if(!isset($this->options['id'])) $this->options['id'] = $this->getId();
        $select = Html::dropDownList($this->name, null, $this->items, $this->options);
        echo Html::tag('div', $select);
        $this->registerClientScript();
    }

    public function registerClientScript()
    {
        $view = $this->view;
        $asset = LinkageAsset::register($view);
        $id = $this->options['id'];

        $this->clientOptions['select'] = "#$id";
        $this->clientOptions['selClass'] = 'form-control';
        $this->clientOptions['selStyle'] = 'max-width: 150px; margin-right: 15px;display: inline-block;';
        $this->clientOptions['ajax'] = Url::to([$this->clientOptions['ajax']]);
        $this->clientOptions['head'] = '请选择...';
        $this->clientOptions['loaderImg'] = $asset->baseUrl .'/loading.gif';
        $options = $this->clientOptions !== false && !empty($this->clientOptions)
            ? Json::encode($this->clientOptions)
            : '';

        $js = "var linkage_$id = new LinkageSel($options);";

        if($this->onChange) {
            $js .= "linkage_$id.onChange($this->onChange);";
        }

        $view->registerJs($js);
    }
}
